from fastapi import APIRouter, Header

from model.db.mapper.experiment_mapper import get_water_experiment_list, add_water_experiment, \
    get_water_experiment, update_water_experiment, get_water_experimentbycore, updateWaterExperimentBasic
from model.params.experiment_params import GetExperimentParam, AddExperimentParam, DeleteExperimentParam, \
    DetailExperimentParam, UpdateExperimentParam, waterExperimentUpdate
from util import objs_to_dict, success_res, SuccessCode, obj_to_dict, error_res, ErrorCode

experiment_type = 'block'
block_router = APIRouter(prefix="/block")


@block_router.post("/list", name="水锁实验列表")
async def get_experiment_list(param: GetExperimentParam, token=Header('token')):
    exp = get_water_experiment_list(param.pitUnits, param.date,experiment_type)
    return success_res(objs_to_dict(exp), SuccessCode.GET)


@block_router.post("/add", name="添加水锁实验")
async def add_experiment_list(param: AddExperimentParam, token=Header('token')):
    core = add_water_experiment(param.core_id, param.date,experiment_type)
    return success_res(obj_to_dict(core), SuccessCode.GET)


@block_router.post("/updateBasic", name="更新水锁实验")
async def update_experiment(param: waterExperimentUpdate, token=Header('token')):
    updateWaterExperimentBasic(param.delete, param.update,experiment_type)
    return success_res('', SuccessCode.PUT)


@block_router.post("/detail", name="水锁实验详情数据")
async def detail_experiment(param: DetailExperimentParam, token=Header('token'),):
    # 获取实验
    exp = get_water_experimentbycore(param.id,experiment_type)
    if exp is None:
        res_code = ErrorCode.DATA_NOT_EXISTED
        res_code['message'] = res_code["message"].format("实验")
        return error_res(res_code)
    # 获取数据
    experiment, experiment_data = get_water_experiment(exp.Core_ID,experiment_type)
    experiment_data = objs_to_dict(experiment_data)
    experiment = obj_to_dict(experiment)
    experiment['data'] = experiment_data
    return success_res(experiment, SuccessCode.GET)


@block_router.post("/update", name="更新水锁详情实验")
async def updte_experiment(param: UpdateExperimentParam, token=Header('token')):
    bool = update_water_experiment(param,experiment_type)
    if bool == 1:
        return success_res(bool, SuccessCode.PUT)
    else:
        return error_res(bool, ErrorCode.PATCH)
